package org.axed.user.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Timer;

/**
 * Displays the caret in an Axed widget. 
 *
 * This class listens to events fired by the widget to reposition the caret.
 */
public class Caret extends CaretBase implements AxedListener {
	/**
	 * Constructor.
	 */
	Caret(AxedArea axed) {
		super(axed, true);
	}

	/** 
	 * The caret is not be shown if not enabled
	 */
	boolean enabled = true;

	/**
	 * True if having the focus.
	 */
	boolean focus = false;

	public void setEnabled(boolean e) {
		if (e == enabled) {
			return;
		}
		enabled = e;
		if (!focus) {
			return;
		}
		if (e) {
			show();
		} else {
			hide();
		}
	}

	/** 
	 * Handles events generated by AxedArea. 
	 * Positions the caret when necessary.
	 */
	public void onAxedEvent(AxedEvent event) {
		switch (event.type) {
		case AxedEvent.FONT_SIZE_CHANGED :
		case AxedEvent.MOVE_CURSOR : 
		case AxedEvent.REFRESH : 
			if (shown) {
				position();
			}
			break;
		case AxedEvent.SCROLL :
			if (shown) {
				setCaretDiv();
			}
			break;
		case AxedEvent.BLUR :
			focus = false;
			if (enabled) {
				hide();
			}
			break;
		case AxedEvent.FOCUS :
			focus = true;
			if (enabled) {
				show();
				position();
			}
			break;
		case AxedEvent.SET_CARET_ENABLED :
			setEnabled(event.getSetCaretEnable().enabled);
			break;
		}
	}
}
